#include <func.h>

int main()
{
    int clientfd = socket(AF_INET,SOCK_STREAM,0);
    if(clientfd < 0){
        perror("socket");
        return EXIT_FAILURE;
    }

    struct sockaddr_in serveraddr;
    memset(&serveraddr,0,sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(8000);
    serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    int ret = connect(clientfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr));
    if(ret < 0) {
        perror("connect");
        return EXIT_FAILURE;
    }

    printf("connect success\n");

    fd_set readfds;

    char buf[1000] = {0};

    while(1){
        FD_ZERO(&readfds);
        FD_SET(STDIN_FILENO,&readfds);
        FD_SET(clientfd,&readfds);

        int ret = select(clientfd + 1,&readfds,NULL,NULL,NULL);
        printf("%d fd ready\n",ret);

        if(FD_ISSET(STDIN_FILENO,&readfds)){
            memset(buf,0,sizeof(buf));
            ret = read(STDIN_FILENO,buf,sizeof(buf));
            printf("read %d bytes\n",ret);

            ret = send(clientfd,buf,strlen(buf),0);
            printf("send %d bytes,content is %s\n",
                   ret,buf);
        }

        if(FD_ISSET(clientfd,&readfds)){
            memset(buf,0,sizeof(buf));
            ret = recv(clientfd,buf,sizeof(buf),0);
            if(ret == 0){
                printf("server closed\n");
                close(clientfd);
                break;
            }
            printf("recv %d bytes\n",ret);
        }
        
    }

    close(clientfd);
        
    return 0;
}

